// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import config from "../config/config";
import func from "../config/func";

const { ccclass, property } = cc._decorator;
//子节点x差值为140， y差值为80
@ccclass
export default class Waiter extends cc.Component {

    n_index: number = 0;
    n_move: boolean = false;
    n_startPos: cc.Vec2 = cc.v2(-20, -160);
    n_food: cc.Sprite = null;

    start() {
        this.creatWaiter();
    }
    /**
     * 创建服务生
     */
    async creatWaiter() {
        for (let i = 0; i < 4; i++) {
            let child: cc.Node = null;
            if (config.prefabArr[config.prefabPath.waiter]) {
                child = cc.instantiate(config.prefabArr[config.prefabPath.waiter]);
            } else {
                let prefab = await func.loadResouce(config.prefabPath.waiter, cc.Prefab) as cc.Prefab;
                config.prefabArr[config.prefabPath.waiter] = prefab;
                child = cc.instantiate(prefab);
            }
            child.parent = this.node;
            child.setPosition(cc.v2(this.n_startPos.x - 140 * i, this.n_startPos.y - 80 * i));
        }
    }
    /**
     * 开始送菜
     */
    moveWaiter(spr: cc.SpriteFrame) {
        if (this.n_move) return;
        this.n_move = true;
        let _index = this.n_index % this.node.childrenCount;
        this.n_food = this.node.children[_index].children[1].children[0].getComponent(cc.Sprite);
        this.n_food.node.active = true;
        this.n_food.spriteFrame = spr;
        cc.tween(this.node.children[_index])
            .to(3, { x: cc.winSize.width / 2, y: -430 })
            .call(() => {
                this.node.children[_index].children[1].children[0].active = false;
                this.node.children[_index].setPosition(cc.v2(-460, -420));
                this.n_index++;
                this.n_move = false;
            })
            .start();

        let len = this.node.children.length - 1,
            startIndex = this.n_index + 1;
        while (len > 0) {
            len--;
            let child = this.node.children[startIndex % this.node.childrenCount];
            cc.tween(child)
                .to(1, { x: child.x + 140, y: child.y + 80 })
                .start();
            startIndex++;
        }
    }

}
